package put.cs.two.to.tsp.models;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class TSPEdgesSolution extends TSPSolution {
    private List<Edge> edges = new LinkedList<Edge>();

    @Override
    public int getCycleLength() {
        int cycleLength = 0;
        for (Edge edge : edges) {
            cycleLength += edge.getLength();
        }
        return cycleLength;
    }

    public Iterable<Edge> edges() {
        return edges;
    }

    @Override
    public String toString() {
        Edge firstEdge = edges.get(0);
        if (firstEdge == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(getCycleLength() + " = ");
        Point from = firstEdge.getFromPoint();
        sb.append(from.getIndex() + " ");
        for (Edge edge : edges) {
            Point to = edge.getAnotherPoint(from);
            sb.append(to.getIndex() + " ");
            from = to;
        }
        return sb.toString();
    }

    public void addEdge(Edge edge, int position) {
        edges.add(position, edge);
    }

    public void applyMove(Edge edgeToBeExtensioned, Point point) {
        ListIterator<Edge> it = edges.listIterator();
        while (it.hasNext()) {
            Edge edge = it.next();
            if (edge.equals(edgeToBeExtensioned)) {
                Edge newEdgeToPoint = new Edge(edgeToBeExtensioned.getFromPoint(), point);
                Edge newEdgeFromPoint = new Edge(point, edgeToBeExtensioned.getToPoint());
                it.set(newEdgeToPoint);
                it.add(newEdgeFromPoint);
            }
        }
    }
}
